<template>
  <view class="custom-tab-bar" v-show="isShowTabBar">
    <view 
      class="tab-bar-item" 
      :class="{ 'active': currentPage === item.pagePath }" 
      v-for="(item, index) in tabBarList" 
      :key="index"
      @click="switchTab(item.pagePath)"
    >
      <image 
        :src="currentPage === item.pagePath ? item.selectedIconPath : item.iconPath" 
        mode="aspectFit"
        class="tab-icon"
      ></image>
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
</template>

<script setup >
import { ref, onMounted, computed, getCurrentInstance } from 'vue';
import {onShow } from '@dcloudio/uni-app';

const { proxy } = getCurrentInstance();

// tabBar 数据
const tabBarList = [
  {
    pagePath: 'pages/home/home',
    text: '首页',
    iconPath: '/static/home.png',
    selectedIconPath: '/static/actHome.png'
  },
  {
    pagePath: 'pages/Product/Product',
    text: '智能体',
    iconPath: '/static/aiRob.png',
    selectedIconPath: '/static/AIRobAc.png'
  },
  {
    pagePath: 'pages/Myinfo/Myinfo',
    text: '我的',
    iconPath: '/static/mine.png',
    selectedIconPath: '/static/mineact.png'
  }
];

// 当前页面路径
const currentPage = ref('pages/home/home');

// 是否显示 tabBar
const isShowTabBar = computed(() => {
  // 可以根据需要设置某些页面不显示 tabBar
  return true;
});

// 获取当前页面路径
const getCurrentPagePath = () => {
  const pages = getCurrentPages();
  if (!pages.length) return 'pages/home/home';
  
  const currentPage = pages[pages.length - 1];
  let path = currentPage.route;
  
  // 统一格式为 'pages/xxx/xxx'
  path = path.startsWith('/') ? path.slice(1) : path;
  path = path.startsWith('pages/') ? path : `pages/${path}`;
  
  return path;
};

// 切换页面
const switchTab = (path) => {
  if (currentPage.value === path) return;
  
  currentPage.value = path;
  uni.switchTab({
    url: '/' + path,
    success: () => {},
    fail: (err) => {
      console.error('切换 tab 失败:', err);
      // 如果不是 tabBar 页面，使用 navigateTo
      if (err.errMsg.includes('tabbar')) {
        uni.navigateTo({
          url: '/' + path
        });
      }
    }
  });
};

// 页面加载时获取当前页面路径
onMounted(() => {
  currentPage.value = getCurrentPagePath();
});

// 页面显示时更新当前页面路径
onShow(() => {
  currentPage.value = getCurrentPagePath();
});
</script>

<style scoped>
.custom-tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #1f2128;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-top: 1rpx solid #535252;
  z-index: 999;
}

.tab-bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #fff;
}

.tab-bar-item.active .tab-text {
  color: #2a6aa5;
}

.tab-icon {
  width: 35rpx;  /* 调整图标大小 */
  height: 45rpx; /* 调整图标大小 */
  margin-bottom: 8rpx; /* 调整图标和文字的间距 */
}

.tab-text {
  font-size: 20rpx;
}
</style>
